import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import config from "../config/config";

import $common from "../utils/$common";
import $store from "../utils/$store";
import $global from "../utils/$global";

import routes, { layoutRoute } from "./routes";
import testPaths from "./test";

const loadView = import.meta.glob("../views/**/*.vue");
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  setScrollBehavior(to);


  if (to.meta.needLogin === false) {
    next();
  } else {
    let userData = $common.checklocalStorage("userData");
    if (userData) {
      //判断是否有菜单权限
      if (!$store.state.menusData) {
        //重新获取菜单
        if (config.isTest) {
          getMenus({
            to,
            next,
            routerPath: testPaths,
          });
        } else {
          //调用接口
          getMenus({ to, next, routerPath: [] });
        }
      } else {
        //因firstUrl首次加载未知,创建redirectPage用于重定向路由
        if (to.path == "/redirectPage") {
          next({ path: $store.state.firstUrl, replace: true });
        } else {
          next();
        }
      }
    } else {
      next("/login");
    }
  }
});

router.afterEach((to, from) => {
  getScrollBehavior(from);
});

//记录二级路由的滚动条位置
function getScrollBehavior(from) {
  if (!from.meta.childKeepAlive) {
    return;
  }
  let dom = document.querySelector("#scrollCtx");
  let scrollTop = 0;
  if (dom) {
    scrollTop = dom.scrollTop;
  }
  //scrollList 记录的滚动历史,存在则设置滚动位置,否则加入
  let self = $store.state.scrollList.find((item) => item.path == from.path);
  if (self) {
    self.scrollTop = scrollTop;
  } else {
    $store.state.scrollList.push({
      path: from.path,
      scrollTop,
    });
  }
}
//设置二级路由的滚动距离
function setScrollBehavior(to) {
  let self = $store.state.scrollList.find((item) => item.path == to.path);
  if (self) {
    let dom = document.querySelector("#scrollCtx");
    if (dom) {
      requestAnimationFrame(() => {
        dom.scrollTop = self.scrollTop;
      });
    }
  }
}

//调用接口返回路由权限
function getMenus({ to, next, routerPath }) {
  //构造路由结构,testPaths模拟接口返回数据
  let { firstUrl, layoutList } = setRouter(routerPath);
  setLayoutData(layoutList);

  //存在先删除,避免重复构建兜底路由
  if (router.hasRoute("redirect404")) {
    router.removeRoute("redirect404");
  }

  //路由底部添加一个重定向404兜底路由
  router.addRoute({
    path: "/:pathMath(.*)",
    redirect: "/404",
    name: "redirect404",
  });

  const routerList = router.getRoutes();

  //设置需要缓存的路由
  routerList.forEach((item) => {
    if (item.meta.keepAlive) {
      $store.state.keepAliveList.push(item.path);
    }
    if (item.meta.childKeepAlive) {
      $store.state.childKeepAliveList.push(item.path);
    }
  });

  if (firstUrl) {
    //缓存菜单权限的第一个路由
    console.log("路由权限");
    console.log(routerPath);
    $store.setStateData("menusData", routerPath);
    console.log("首页路径");
    console.log(firstUrl);
    $store.setStateData("firstUrl", firstUrl);
    if (to.path == "/redirectPage") {
      next({ path: $store.state.firstUrl, replace: true });
    } else {
      next({ ...to, replace: true });
    }
  } else {
    $global.openN("暂无权限,请联系管理员", "error");
    $global.loginOut();
    next({ path: "/login", replace: true });
  }
}

//构造路由结构,筛选出layout布局路由
function setRouter(routerPath) {
  let firstUrl = "";
  let layoutList = [];

  routerPath.forEach((item, index) => {
    if (index == 0) {
      firstUrl = item.path;
    }
    if (item.url) {
      let component = loadView[`../${item.url}`];

      //使用该方法可以节省每个vue文件手动导出name属性
      item.component = () => {
        return component().then((comp) => ({
          ...comp.default,
          name: item.path,
        }));
      };
    }

    let v = $common.deepCopy(item);
    delete v.children;

    //layout二级路由
    if (item.path && item.path.includes("layout")) {
      if (!item.children || !item.children.length) {
        layoutList.push(v);
      }
    }
    //常规路由
    else {
      v.name = v.path;
      //退出登录时需要把ordinaryList路由删除
      $store.state.primaryRouteList.push(v);
      router.addRoute(v);
    }

    if (item.children && item.children.length) {
      let childData = setRouter(item.children);
      if (index == 0) {
        firstUrl = childData.firstUrl;
      }
      layoutList = [...layoutList, ...childData.layoutList];
    }
  });

  return { firstUrl, layoutList };
}

//构造layout路由
function setLayoutData(layoutList) {
  layoutRoute.children = layoutList.map((item) => {
    item.meta = {
      title: "layout",
      childKeepAlive: item.keepAlive || false,
    };
    item.name = item.path;
    return item;
  });
  // if (layoutList[0]) {
  //   layoutRoute.redirect = layoutList[0].path;
  // }

  router.addRoute(layoutRoute);
}

export default router;
